# coding=utf-8
import os
import subprocess

from appium import webdriver
from time import strftime, sleep
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from selenium.common.exceptions import TimeoutException
from colorama import init, Fore, Style
init(autoreset=True)

desired_caps = {
    "platformName": "Android",
    "automationName": "uiautomator2",
    "platformVersion": "9",
    "deviceName": '2025061700001872',
    "appPackage": "com.seven.qaml.burstserven",
    "appActivity": "com.seven.qaml.burstserven.ui.MenuActivity",
    'skipServerInstallation': False,
    'skipDeviceInitialization': False,
    "noReset": True
}
appium_server_url = 'http://127.0.0.1:4723'
driver = webdriver.Remote(appium_server_url, desired_caps)
adb_script_path = "/data/local/tmp/press_keys.sh"
adb_command = f'adb shell {adb_script_path}'

sleep(3)
adb_script_path = "/data/local/tmp/press_keys.sh"
adb_check_command = f"adb shell ls {adb_script_path}"
result = subprocess.run(adb_check_command, shell=True, capture_output=True, text=True)
if result.returncode == 0:
    print("获取到起爆脚本:", adb_script_path)
else:
    print('未获取到起爆脚本，正在创建......')
    create_script_command = (
        'adb shell "echo \'for i in $(seq 1 5); do input keyevent 999 & input keyevent 132; done\' > '
        '/data/local/tmp/press_keys.sh && chmod 755 /data/local/tmp/press_keys.sh"'
    )
    subprocess.run(create_script_command, shell=True)
    print("创建起爆脚本成功：", adb_script_path)

count = 0
while count < 100:
    driver.find_element('id', 'com.seven.qaml.burstserven:id/layout_zuWang').click()
    sleep(5)
    while True:
        if driver.find_element('id', 'com.seven.qaml.burstserven:id/text_sign').text == "准备完成，按‘确定’键开始扫描":
            driver.keyevent(66)
            print("等待扫描结果...")
            break
    while True:
        if driver.find_elements('id', 'com.seven.qaml.burstserven:id/tv_message') != []:
            if driver.find_element('id',
                                   'com.seven.qaml.burstserven:id/tv_message').text == '按F1查看列表，确定键继续':
                print("扫描完成")
                driver.keyevent(66)
                sleep(2)
                break
    while True:
        try:
            authnext_element = WebDriverWait(driver, 20).until(
                EC.presence_of_element_located(('id', 'com.seven.qaml.burstserven:id/btn_authnext'))
            )
            if authnext_element.text == '按确定键继续':
                driver.keyevent(66)
                sleep(2)
                break
        except TimeoutException:
            print("等待'按确定键继续'按钮超时，重新尝试...")
            sleep(1)
    charge_text = driver.find_element('xpath',
                                      '/hierarchy/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.LinearLayout[2]/android.widget.TextView[4]')
    if charge_text.text == '按充电键开始充电':
        driver.keyevent(300)
        print("开始充电")
    while True:
        try:
            qibao_text = WebDriverWait(driver, 300).until(
                EC.presence_of_element_located(('xpath', '/hierarchy/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.LinearLayout[2]/android.widget.LinearLayout[1]/android.widget.TextView[1]')))
            if qibao_text.text == '倒计时：':
                print("充电完成")
                result = os.system(adb_command)
                if result == 0:
                    print("成功执行起爆命令")
                    break
        except Exception as e:
            '''
            元素失效，重新查找
            '''
            sleep(1)
            continue
    sleep(10)
    count += 1
    print(Fore.GREEN + f"已完成 {count} 次起爆")